package com.gmrz.uap.tenantconfig;

import com.gmrz.uap.cache.AmmsCacheUtil;
import com.gmrz.uap.cfg.SystemConst;
import com.gmrz.uap.common.ControllerSupport;
import com.gmrz.uap.dict.DictConst;
import com.gmrz.uap.dict.DictService;
import com.gmrz.uap.model.Dict;
import com.gmrz.uap.model.TenantConfig;
import com.gmrz.uap.model.UasConfig;
import com.gmrz.uap.util.Identities;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import redis.clients.jedis.exceptions.JedisConnectionException;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class TenantConfigController extends ControllerSupport {

    private static final Logger LOG = LogManager.getLogger(TenantConfigController.class);
    private static final String UAF_APPLICATIOIN_ID = "uaf.application.id";

    public void index() {
        final String tenantId = getCookie(SystemConst.COOKIE_TENANT_ID);
        final List<TenantConfig> tenantConfigs = TenantConfigService.me.getByTenantId(tenantId);

        //从数据字典中获取需要同步的选项
        final List<Dict> tenantConfigOptionDictList = DictService.me.getDictListByDictTypeID(DictConst.DICT_TYPE_TENANT_CONFIG_OPTONS);

        //交易类型
        List<Dict> transTypeList = DictService.me.getDictListByDictTypeID(DictConst.DICT_TYPE_TRANS_TYPE_ID);

        //从基础配置表中获取数据
        String[] uasConfigParams = new String[tenantConfigOptionDictList.size()];
        for (int i = 0; i < tenantConfigOptionDictList.size(); i++) {
            uasConfigParams[i] = tenantConfigOptionDictList.get(i).getDictText();
        }

        final List<UasConfig> uasConfigList = UasConfig.dao.getByCNameArr(uasConfigParams);


        //如果查到的结果与数据字典中的数量不一致抛出异常
        if (uasConfigList.size() != tenantConfigOptionDictList.size()) throw new RuntimeException();

        for (int z = 0; z < tenantConfigOptionDictList.size(); z++) {
            Dict dict = tenantConfigOptionDictList.get(z);
            if (StrKit.equals(UAF_APPLICATIOIN_ID, dict.getDictText())) {
                String cname = dict.getDictText();
                for (Dict transTypeDict : transTypeList) {
                    Dict tmpDict = new Dict();
                    tmpDict.setDictId(dict.getDictId());
                    tmpDict.setDictName(cname + transTypeDict.getDictText());
                    tmpDict.setDictText(cname + transTypeDict.getDictText());
                    tmpDict.setIsEnable(dict.getIsEnable());
                    tmpDict.setDes(dict.getDes());
                    tenantConfigOptionDictList.add(tmpDict);
                }
                tenantConfigOptionDictList.remove(z);
            }
        }


        boolean flag = Db.tx(new IAtom() {
            @Override
            public boolean run() throws SQLException {

                //如果渠道下渠道配置为空则将数据存储到渠道配置表中
                if (tenantConfigs == null || tenantConfigs.isEmpty()) {
                    for (UasConfig uasConfig : uasConfigList) {
                        boolean isSave = save(tenantId, uasConfig);
                        if (!isSave) return false;
                    }
                } else {
                    for (int i = 0; i < tenantConfigOptionDictList.size(); i++) {
                        Dict dict = tenantConfigOptionDictList.get(i);
                        boolean exist = false;

                        for (int j = 0; j < tenantConfigs.size(); j++) {
                            TenantConfig tenantConfig = tenantConfigs.get(j);
                            //判断数据字典中的配置项是否存在
                            if (StrKit.equals(dict.getDictText(), tenantConfig.getConfigCname())) {
                                exist = true;
                                tenantConfigs.remove(j);
                                break;
                            }
                        }

                        if (!exist) {//如果渠道配置中没有当前配置信息则增加
                            String cname = dict.getDictText();
                            if (cname.startsWith(UAF_APPLICATIOIN_ID)) {
                                cname = UAF_APPLICATIOIN_ID;
                            }

                            UasConfig uasConfig = UasConfig.dao.getByCName(cname);
                            uasConfig.setConfigCname(dict.getDictText());
                            boolean isSave = save(tenantId, uasConfig);
                            if (!isSave) return false;
                        }
                    }

                    if (!tenantConfigs.isEmpty()) {//如果渠道配置列表不为空则删除
                        for (TenantConfig tenantConfig : tenantConfigs) {
                            boolean isDelete = tenantConfig.delete();
                            if (!isDelete) return false;
                        }
                    }
                }

                return true;
            }
        });

        if (!flag) throw new RuntimeException();

        setAttr("tenantConfigs", TenantConfig.dao.getByTenantIdForUserDefault(tenantId));
        setAttr("tenantId", tenantId);


    }

    private boolean save(String tenantId, UasConfig uasConfig) {
        boolean isSave = false;
        TenantConfig tenantConfig = new TenantConfig();
        if (StrKit.equals(UAF_APPLICATIOIN_ID, uasConfig.getConfigCname())) {
            //交易类型
            List<Dict> transTypeList = DictService.me.getDictListByDictTypeID(DictConst.DICT_TYPE_TRANS_TYPE_ID);
            for (Dict dict : transTypeList) {
                tenantConfig.setTcId(Identities.uuid2());
                tenantConfig.setTenantId(tenantId);
                tenantConfig.setConfigCname(uasConfig.getConfigCname() + dict.getDictText());
                tenantConfig.setConfigEname(uasConfig.getConfigEname());
                tenantConfig.setConfigValue(uasConfig.getConfigValue());
                tenantConfig.setDataType(uasConfig.getDataType());
                tenantConfig.setRegex(uasConfig.getRegex());
                tenantConfig.setTransType(dict.getDictText());
                tenantConfig.setErrorMsg(uasConfig.getErrorMsg());
                isSave = tenantConfig.save();
                if (!isSave) break;
            }
        } else {
            tenantConfig.setTcId(Identities.uuid2());
            tenantConfig.setTenantId(tenantId);
            tenantConfig.setConfigCname(uasConfig.getConfigCname());
            tenantConfig.setConfigEname(uasConfig.getConfigEname());
            tenantConfig.setConfigValue(uasConfig.getConfigValue());
            tenantConfig.setDataType(uasConfig.getDataType());
            tenantConfig.setRegex(uasConfig.getRegex());
            tenantConfig.setErrorMsg(uasConfig.getErrorMsg());
            isSave = tenantConfig.save();
        }

        return isSave;
    }


    public void edit() {
        TenantConfig tenantConfig = getModel(TenantConfig.class);
        flag = tenantConfig.update();

        if (flag) {
            message = "渠道配置信息更新成功!";
        } else {
            message = "渠道配置信息更新失败，请稍后重试!";
        }

        try {
            if (flag) {
                StringBuilder tenantConfigKey = new StringBuilder();
                tenantConfigKey.append(tenantConfig.getConfigEname());
                tenantConfigKey.append(tenantConfig.getTenantId());
                if ("uaf.application.id".equals(tenantConfig.getConfigEname())) {
                    message = AmmsCacheUtil.deleteIfSuccess(tenantConfigKey.toString() + ".00", message);
                    message = AmmsCacheUtil.deleteIfSuccess(tenantConfigKey.toString() + ".01", message);
                    message = AmmsCacheUtil.deleteIfSuccess(tenantConfigKey.toString() + ".02", message);
                } else {
                    message = AmmsCacheUtil.deleteIfSuccess(tenantConfigKey.toString(), message);
                }
            }
        } catch (JedisConnectionException jedisConnectionException) {
            message += getRes().get("redis.connection.failed");
            LOG.error(message, jedisConnectionException);
        }


        result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
        result.put(SystemConst.MESSAGE_RESULT_MSG, message);

        render(responseJsonRender(result));
    }
}
